package com.vframework.config.freemarker.dict;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.vframework.base.model.BaseBean;
import com.vframework.common.service.DictService;
import com.vframework.config.freemarker.CustomDirective;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

@Component
public class DictDirective extends CustomDirective {
    
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        if (params.isEmpty()) {
            throw new TemplateModelException("This directive doesn't allwow empty parameters.");
        }
        if (params.containsKey("type") && !params.containsKey("value")) {
            String type = params.get("type").toString();
            List<BaseBean> dictList = DictService.getTypeList(type);
            env.setVariable("dictList", getBeansWrapper().wrap(dictList));
        } else if (params.containsKey("type") && params.containsKey("value")) {
            String type = params.get("type").toString();
            String value = params.get("value").toString();
            String typeName = DictService.getTypeName(type, value);
            env.setVariable("typeName", getBeansWrapper().wrap(typeName));
        }
        render(env, params, body);
    }

    @Override
    public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
        if (body != null) {
            body.render(env.getOut());
        } else {
            throw new RuntimeException("标签内部内容为空!");
        }
    }
}
